package com.example.demo.service;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.entity.ContentType;
import org.apache.http.nio.entity.NStringEntity;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.Collections;

/**
 * Created by wangyg6 on 2020/8/4 14:26.
 */
@Service
public class ElasticSearchService {
	private static final Logger log = LoggerFactory.getLogger(ElasticSearchService.class);

	private RestClient client;
	@Value("${rule.log.es.hostname}")
	private String hostname;
	@Value("${rule.log.es.port}")
	private Integer port;

	@PostConstruct
	private void initClient() {
		client = RestClient.builder(new HttpHost(hostname, port, "http")).build();
	}


	/**
	 * 查询规则日志，包含入参，host等
	 * @return
	 * @throws IOException
	 */
	public String search(String keyword, String type) throws IOException {
		//		initClient();

/*		BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery();
		SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
		MatchQueryBuilder matchQueryBuilder = QueryBuilders
				.matchQuery("logObj.log_id", logId);//这里可以根据字段进行搜索，must表示符合条件的，相反的mustnot表示不符合条件的
		// RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("fields_timestamp"); //新建range条件
		// rangeQueryBuilder.gte("2019-03-21T08:24:37.873Z"); //开始时间
		// rangeQueryBuilder.lte("2019-03-21T08:24:37.873Z"); //结束时间
		// boolBuilder.must(rangeQueryBuilder);
		boolBuilder.must(matchQueryBuilder);
		sourceBuilder.query(boolBuilder); //设置查询，可以是任何类型的QueryBuilder。
		sourceBuilder.from(0); //设置确定结果要从哪个索引开始搜索的from选项，默认为0
		sourceBuilder.size(10); //设置确定搜素命中返回数的size选项，默认为10
		sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS)); //设置一个可选的超时，控制允许搜索的时间。

		sourceBuilder.fetchSource(new String[] { "fields.port", "fields.entity_id", "fields.message" },
				new String[] {}); //第一个是获取字段，第二个是过滤的字段，默认获取全部
		SearchRequest searchRequest = new SearchRequest("customer"); //索引
		searchRequest.types("doc"); //类型
		searchRequest.source(sourceBuilder);
		SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
		SearchHits hits = response.getHits();  //SearchHits提供有关所有匹配的全局信息，例如总命中数或最高分数：
		SearchHit[] searchHits = hits.getHits();
		for (SearchHit hit : searchHits) {
			log.info("search -> {}", hit.getSourceAsString());
		}*/
		/*BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery();
		SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
		TermQueryBuilder term1 = QueryBuilders.termQuery("logObj.uri", "checkOrderCommit");//规则日志具体方法名
		boolBuilder.must(term1);
		//通过logId或者input的购物车前缀都可以查到
		if (type.equals("logId")) {
			TermQueryBuilder term2 = QueryBuilders.termQuery("logObj.log_id", keyword);
			boolBuilder.must(term2);
		} else if (type.equals("olId")) {
			PrefixQueryBuilder prefix1 = QueryBuilders.prefixQuery("logObj.input", keyword);
			boolBuilder.must(prefix1);
		}
		SearchResponse response = client.search(new SearchRequest()
						.source(sourceBuilder.query(boolBuilder).from(0).size(10).timeout(new TimeValue(20, TimeUnit.SECONDS))),
				RequestOptions.DEFAULT);
		SearchHits hits = response.getHits();  //SearchHits提供有关所有匹配的全局信息，例如总命中数或最高分数：
		SearchHit[] searchHits = hits.getHits();
		for (SearchHit hit : searchHits) {
			log.info("search -> {}", hit.getSourceAsString());
		}

		return Arrays.toString(searchHits);*/

		String method = "POST";
		String endPoint = "_search";
		String prefix = "{" + "  \"query\": {" + "    \"bool\": {" + "      \"must\": [" + "        {";
		String postfix = " }" + "        }," + "        {" + "          \"term\": {"
				+ "            \"logObj.uri.keyword\": \"checkOrderCommit\"" + "          }" + "        }" + "      ]"
				+ "    }" + "  }," + "  \"from\": 0," + "  \"size\": 10" + "}";
		String suffix = "";
		if (type.equals("logId")) {
			suffix = " \"term\": {" + "            \"logObj.log_id.keyword\":\"" + keyword + "\"";
		} else if (type.equals("olId")) {
			suffix = " \"prefix\": {" + "            \"logObj.input.keyword\":\"" + keyword + "\"";
		}
		HttpEntity entity = new NStringEntity(prefix + suffix + postfix, ContentType.APPLICATION_JSON);

		Response response = client.performRequest(method, endPoint, Collections.emptyMap(), entity);
		return EntityUtils.toString(response.getEntity());

	}

}
